const path = require('path')
const fs = require('fs')
const getFileName = require('./get-filename')
let tmp = require('./tmp')

async function merge(chunkCount, fileName) {
  let filename = getFileName(fileName)
  let index = 0
  let dirPath = path.join(tmp, filename)
  let dist = path.join(tmp, fileName)
  let distStream = fs.createWriteStream(dist)
  while (index < chunkCount) {
    await new Promise(resolve => {
      let stream = fs.createReadStream(path.join(dirPath, index + ''))
      stream.pipe(distStream, { end: false })
      stream.on('end', () => {
        index++
        resolve()
      })
    })
  }
  distStream.close()
  return dist
}

module.exports = merge

// merge(138, 'data.zip')
